<template>
    <el-form :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px" ref="formRef">
        <el-form-item label="事项主题" prop="title">
            <el-input v-model="formData.title" placeholder="请填写事项主题" clearable maxlength="32"/>
        </el-form-item>
        <el-form-item label="事项描述" prop="content">
            <el-input v-model="formData.content" placeholder="请填写事项描述" type="textarea" :rows="3"/>
        </el-form-item>
        <el-form-item label="申请日期" prop="occurDate">
            <el-date-picker v-model="formData.occurDate" type="date" placeholder="请选择申请日期" size="small" value-format="YYYY-MM-DD" @change="dateChange"/>
        </el-form-item>
        <el-form-item label="关联" prop="customerId">
            <el-select v-model="selectedCustomer" :disabled="customerDisable" placeholder="请选择客户" value-key="id" clearable filterable @change="customerChange">
                <el-option v-for="customer in customers" :key="customer.id" :label="customer.nickname" :value="customer"/>
            </el-select>
            <el-select v-model="selectedOrders" :placeholder="formData.customerId ? '请选择订单' : '请先选择客户'" :disabled="formData.customerId == null || formData.customerId == ''" value-key="id" clearable filterable multiple style="margin: 0 10px" collapse-tags collapse-tags-tooltip>
                <el-option v-for="order in orders" :key="order.id" :label="order.orderSn" :value="order"/>
            </el-select>
        </el-form-item>
        <el-form-item label="发票类型" prop="invoiceType">
            <el-select v-model="formData.invoiceType" placeholder="请选择发票类型" clearable filterable>
                <el-option v-for="item in typeList" :key="item.value" :label="item.name" :value="item.value"/>
            </el-select>
        </el-form-item>
        <el-form-item label="开票金额" prop="amount">
            <el-input-number v-model="formData.amount" :controls="false" :precision="2" :min="0.01"/>
        </el-form-item>

        <el-divider content-position="left">开票信息</el-divider>
        <el-form :model="invoiceInfo" :rules="invoiceRules" size="small" :inline="false" label-width="100px" ref="invoiceForm" style="margin-bottom: 18px">
            <el-row>
                <el-col :span="12" style="margin-bottom: 18px">
                    <el-form-item label="发票抬头" prop="purchaser">
                        <el-input v-model="invoiceInfo.purchaser" placeholder="请填写发票抬头" clearable maxlength="32"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="纳税人识别号">
                        <el-input v-model="invoiceInfo.taxpayerIdNo" clearable placeholder="请填写纳税人识别号" maxlength="32"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="地址">
                <el-input v-model="invoiceInfo.address" type="textarea" :rows="2" maxlength="128" placeholder="请填写地址"/>
            </el-form-item>
            <el-row style="margin-bottom: 18px">
                <el-col :span="12">
                    <el-form-item label="电话" prop="telephone">
                        <el-input v-model="invoiceInfo.telephone" clearable placeholder="请填写电话" maxlength="16"/>
                    </el-form-item>
                    <el-form-item label="银行账号" prop="bankAccount">
                        <el-input v-model="invoiceInfo.bankAccount" placeholder="请填写银行账号" clearable maxlength="32"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="开户银行" prop="openingBank">
                        <el-input v-model="invoiceInfo.openingBank" placeholder="请填写开户银行" clearable maxlength="100"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="margin-bottom: 18px">
                <el-col :span="12">
                    <el-form-item label="收件人" prop="receiveName">
                        <el-input v-model="invoiceInfo.receiveName" placeholder="请填写收件人名称" clearable maxlength="32"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="收件人电话" prop="checkTakerPhone">
                        <el-input v-model="invoiceInfo.checkTakerPhone" placeholder="请填写收件人电话" clearable maxlength="16"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="邮寄地址">
                <el-input v-model="invoiceInfo.postAddress" placeholder="请填写邮寄地址" type="textarea" :rows="2" maxlength="200"/>
            </el-form-item>
        </el-form>
        <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请填写备注" type="textarea" :rows="3" maxlength="500"/>
        </el-form-item>
        <el-form-item label="确认人" prop="executorIds">
            <el-select v-model="formData.executorIds" placeholder="请选择确认人" clearable filterable multiple collapse-tags collapse-tags-tooltip>
                <el-option v-for="item in confirmUsers" :key="item.userId" :label="item.userName" :value="item.userId"/>
            </el-select>
        </el-form-item>
        <el-form-item label="抄送人">
            <el-button type="primary" @click="openPicker" icon="ele-User">选择抄送人</el-button>
            <el-tag v-for="(user, i) in copyUsers" :key="user.id" style="margin-left: 10px" closable @close="removeUser(i)">{{ user.name }}</el-tag>
        </el-form-item>
        <el-form-item label="发票号" v-if="formData.offerNo || moneyFlag">
            <el-input v-model="formData.offerNo" maxlength="64" :disabled="!moneyFlag"/>
        </el-form-item>

        <el-row justify="end">
            <el-button size="default" @click="closeForm">关闭</el-button>
            <!-- 日历/事项列表编辑处理 -->
            <el-button size="default" type="primary" v-if="!formData.id && !formData.agendaMatterId" @click="submitData(formRef, invoiceForm)">保存</el-button>
            <el-button size="default" type="primary" v-else-if="formData.state == 0 || formData.state == 1" @click="matterConfirm">确认</el-button>
        </el-row>

        <org-picker ref="orgPicker" title="请选择抄送人" multiple type="user" :selected="copyUsers" @ok="confirmPick"/>
    </el-form>
</template>

<script>
// 开票申请

import Document from '/@/components/document/index.vue'
import {toRefs, ref, reactive, onMounted} from 'vue'
import invoiceApi from '/@/api/ums/customer/invoice'
import {formatDate} from '/@/utils/formatTime'
import {getRelatableId, getRelatableMap} from '/@/api/matter'
import moneyApi from '/@/api/money'
import moneyMatterApi from '/@/api/matter/money'
import relateItemApi from '/@/api/matter/relateItem'
import customerApi from '/@/api/ums/customer'
import {ElMessage} from 'element-plus'
import Cookies from 'js-cookie'
import {homeApi} from '/@/api/home'
import OrgPicker from '/@/views/setting/workflow/process/OrgPicker.vue'
import {getDictByCodes} from '/@/api/sys/dict'

export default {
    name: 'InvoiceDispatch',
    emits: ['update:code'],
    props: {
        editId: {
            default: null,
            type: String
        },
        code: {
            default: null,
            type: String
        },
        customerId: {
            default: null,
            type: String
        },
        selectTime: {
            default: null,
            type: String
        },
        relatableMap: {
            type: Object,
            default: null
        }
    },
    components: {
        Document,
        OrgPicker
    },
    setup(props, context) {
        const {customerId, selectTime, editId, relatableMap} = toRefs(props)
        const formRef = ref()
        const invoiceForm = ref()
        const orgPicker = ref()
        const state = reactive({
            formData: {
                title: '开票申请',
                type: 'INVOICE_DISPATCH',
                executorIds: [],
                agendaMatterId: null
            },
            formRules: {
                title: {required: true, message: '请填写事项主题', trigger: 'blur'},
                executorIds: {required: true, message: '请选择确认人', trigger: 'change'},
                amount: {required: true, message: '请填写开票金额', trigger: 'blur'}
            },
            invoiceInfo: {    // 客户的开票信息
                id: null,
                customerId: null,
                purchaser: null,
                address: null,
                telephone: null,
                taxpayerIdNo: null,
                openingBank: null,
                bankAccount: null,
                invoiceType: '1',
                invoiceTitle: null,
                checkTakerPhone: null,
                checkTakerMail: null,
                postAddress: null,
                receiveName: null
            },
            invoiceRules: {
                purchaser: {required: true, message: '请填写发票抬头', trigger: 'blur'},
                telephone: [{required: true, message: '请填写电话', trigger: 'blur'}, {pattern: /^[1]([3-9])[0-9]{9}$/, message: '请填写正确的手机号', trigger: 'blur'}],
                openingBank: {required: true, message: '请填写开户银行', trigger: 'blur'},
                bankAccount: {required: true, message: '请填写银行账户', trigger: 'blur'},
                receiveName: {required: true, message: '请填写收件人名称', trigger: 'blur'},
                checkTakerPhone: [{required: true, message: '请填写收件人电话', trigger: 'blur'}, {pattern: /^[1]([3-9])[0-9]{9}$/, message: '请填写正确的手机号', trigger: 'blur'}]
            },
            relatableItem: null,    // 可关联项map
            typeList: [],       // 发票类型字典列表
            copyUsers: [],      // 默认选中的抄送人列表
            customerDisable: false,   // 是否禁选客户
            customers: [],    // 客户列表
            orders: [],   // 订单列表
            selectedOrders: [],   // 选择的订单列表
            selectedCustomer: null,   // 选择的客户
            confirmUsers: [],   // 确认人列表
            moneyFlag: false      // 是否钱人员
        })

        const initData = () => {
            state.formData = {
                id: null,
                title: '开票申请',
                type: 'INVOICE_DISPATCH',
                executorIds: [],
                copyIds: [],    // 抄送人id列表
                agendaMatterId: null,
                invoiceType: '1',   // 字典InvoiceType
                content: '',
                occurDate: null,
                actionStartTime: null,
                actionEndTime: null,
                relateItems: [],
                remark: null,
                attach: '',
                attachNames: '',
                priority: 0,
                remindState: 'NONE',
                amount: 0,
                offerNo: null,    // 发票号
                capitalStreamNo: null,    // 钱相关事项特有流水号, 系统自动生成
                capitalTypeId: null,
                capitalAccountId: null,
                customerInvoiceId: null,
                customerId: customerId.value || null,    // 表单校验
                targetData: {
                    id: null,
                    type: 1,
                    name: null
                }
            }
            state.invoiceInfo = {
                id: null,
                customerId: null,
                purchaser: null,
                address: null,
                telephone: null,
                taxpayerIdNo: null,
                openingBank: null,
                bankAccount: null,
                invoiceType: 0,
                invoiceTitle: null,
                checkTakerPhone: null,
                checkTakerMail: null,
                postAddress: null,
                receiveName: null
            }
            getDictByCodes(['InvoiceType']).then(res => state.typeList = res.data['InvoiceType']).catch(e => console.log(e))
        }
        const customerChange = (customer) => {
            if (!customer || !customer.id) {
                return ElMessage.warning('请先选择客户！')
            }
            state.formData.targetData.id = state.formData.customerId = customer.id
            state.formData.targetData.name = customer.nickname
            // 获取客户开票信息
            invoiceApi.getInvoice(customer.id).then(res => {
                if (res.data) {
                    state.invoiceInfo = res.data
                    state.formData.customerInvoiceId = state.invoiceInfo.id
                }
            }).catch(e => console.log(e))
            // 获取订单
            relateItemApi.getOrderList(customer.id).then(res => state.orders = res.data).catch(e => console.log(e))
        }
        const dateChange = (val) => {
            if (val) {
                state.formData.actionEndTime = state.formData.actionStartTime = val + state.formData.actionStartTime.substring(10)
            }
        }
        const getCustomers = async () => {
            let res
            if (state.moneyFlag) {
                res = await relateItemApi.getCustomerList()
            } else {
                res = await customerApi.getList()
            }
            state.customers = res.data
            for (let i = 0; i < state.customers.length; i++) {
                let customer = state.customers[i]
                if (state.formData.customerId == customer.id) {
                    state.selectedCustomer = customer
                    customerChange(customer)
                    break
                }
            }
        }
        const initConfirmUser = () => {
            // 获取确认人列表（钱模块）
            moneyApi.getCapitalUsers('capitalStream').then(res => {
                state.confirmUsers = res.data
                // 判断当前用户是否钱确认人员之一
                let selfId = Cookies.get('userId')
                for (let i = 0; i < state.confirmUsers.length; i++) {
                    let confirmUser = state.confirmUsers[i]
                    if (confirmUser.userId == selfId) {
                        state.moneyFlag = true
                        getCustomers()
                        break
                    }
                }
                if (!editId.value) {    // 非编辑
                    // 获取确认人的历史选择记录
                    moneyApi.getConfirmRecord(state.formData.type).then(res => {
                        if (res.data) {
                            state.formData.executorIds = []
                            res.data.forEach(confirmId => {
                                for (let i = 0; i < state.confirmUsers.length; i++) {
                                    let confirmUser = state.confirmUsers[i]
                                    if (confirmUser.userId == confirmId) {
                                        state.formData.executorIds.push(confirmId)
                                        break
                                    }
                                }
                            })
                        } else if (state.moneyFlag) {  // 没有历史选择记录 且为确认人之一
                            state.formData.executorIds = [state.selfId]
                        }
                    }).catch(e => console.log(e))
                }
            }).catch(e => console.log(e))
        }
        const openPicker = () => {
            orgPicker.value.show()
        }
        // 抄送人确认选择回调
        const confirmPick = (users) => {
            if (users && users.length > 0) {
                state.copyUsers = users
                state.formData.copyIds = []
                users.forEach(user => state.formData.copyIds.push(user.id))
            } else {
                state.copyUsers = state.formData.copyIds = []
            }
        }
        // 抄送人标签移除方法
        const removeUser = (index) => {
            state.copyUsers.splice(index, 1)
            state.formData.copyIds.splice(index, 1)
        }
        const submitData = async (formEl, invoiceEl) => {
            try {
                let valid = await formEl.validate()
                if (!valid) {
                    return false
                }
                valid = await invoiceEl.validate()
                if (!valid) {
                    return false
                }
                let relatable = state.relatableItem['Customer']
                state.formData.relateItems = [{
                    code: relatable.code,
                    agendaMatterRelatableId: relatable.id,
                    seRelateDataId: state.formData.customerId,
                    label: relatable.label + '/' + state.selectedCustomer.nickname
                }]

                if (state.selectedOrders != null && state.selectedOrders.length > 0) {
                    relatable = state.relatableItem['Order']
                    state.selectedOrders.forEach(order => state.formData.relateItems.push({
                        code: relatable.code,
                        agendaMatterRelatableId: relatable.id,
                        seRelateDataId: order['id'],
                        label: relatable.label + '/' + order['orderSn']
                    }))
                }
                moneyMatterApi.submitMatter(state.formData).then(res => {
                    if (res.data) {
                        // 修改客户开票信息
                        invoiceApi.edit(state.invoiceInfo).catch(e => console.log(e))
                        ElMessage.success('提交成功！')
                        closeForm()
                    }
                }).catch(e => console.log(e))
            } catch (e) {
                console.log(e)
            }
        }
        const matterConfirm = () => {
            moneyMatterApi.moneyConfirm(state.formData).then(res => {
                if (res.data) {
                    ElMessage.success('确认成功！')
                    closeForm()
                }
            }).catch(e => console.log(e))
        }
        const closeForm = () => context.emit('update:code', '')

        onMounted(() => {
            if (relatableMap.value == null) {
                getRelatableMap().then(res => state.relatableItem = res.data).catch(e => console.log(e))
            } else {
                state.relatableItem = JSON.parse(JSON.parse(relatableMap.value))
            }
            initData()
            if (editId.value) {
                homeApi().getInfo({id: editId.value}).then(res => {
                    if (res.data) {
                        let matter = res.data
                        let matterInfo = matter.info
                        state.formData = {
                            agendaMatterId: matter.id,
                            type: matter.code,
                            title: matter.title,
                            content: matter.content,
                            amount: matterInfo.amount,
                            invoiceType: matterInfo.invoiceType,
                            offerNo: matterInfo.offerNo,
                            capitalStreamNo: matterInfo.capitalStreamNo,
                            occurDate: matterInfo.occurDate,
                            customerInvoiceId: matterInfo.customerInvoiceId,
                            approvalState: matter.approvalState,
                            customerId: null,
                            state: matter.state,
                            sponsor: matter.sponsor,   // 发起人信息
                            executors: matter.executors,
                            executorIds: matter.executors.map(item => item.userId),
                            targetData: {
                                id: null,
                                type: 1,
                                name: null
                            }
                        }
                        matter.relateItems.forEach(item => {
                            if (item.label.indexOf('客') > -1) {
                                state.formData.customerId = item.seRelateDataId
                            }
                        })
                        initConfirmUser()
                    }
                }).catch(e => console.log(e))
            } else {
                initConfirmUser()
                // 行动时间默认现在
                let nowTime = selectTime.value || formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS')
                state.formData.actionStartTime = state.formData.actionEndTime = nowTime
                state.formData.occurDate = nowTime.substring(0, 10)
            }
        })

        return {
            formRef,
            orgPicker,
            invoiceForm,
            ...toRefs(state),
            submitData,
            closeForm,
            dateChange,
            customerChange,
            matterConfirm,
            openPicker,
            confirmPick,
            removeUser
        }
    }
}
</script>

<style scoped lang="scss">

</style>
